﻿﻿﻿/***************************  Ccay IGrid Editor  ***********************************/
(function(IGrid,Const){
	var rowRenderMsg = Const.I18n.rowRender = {
		rowRenderSet : "ccay.common.igrid.rowRenderSet",
		rowSpanCol: "ccay.common.igrid.rowSpanCol",
		groupCol: "ccay.common.igrid.groupCol",
		rowRenderMsg: "ccay.common.message.rowRenderMsg",
		noSelectedMsg: "ccay.common.message.noSelectExist"
	};
	
	function getSortType(type){
		return (type === "desc") ? "desc" : "asc";
	}
	
	function getFields(order){
		var fields = [];
		if(order && order.length > 0){
			$.each(order,function(){
				fields.push(this.field);
			})
		}
		return fields;
	}
	
	//行渲染适配器
	IGrid.rowRender = $.IAdapter();
	
	//注册行渲染插件
	Ccay.UI.XControl.addPlugin("XGrid", "rowRender", {
		preInit : function(grid, op){
			if(op.rowRender && !op._reIniting ){
	    		var render = IGrid.rowRender.get(op.rowRender);
	    		render && render.init &&  render.init(grid, op); 
	    		grid.setSortSetting();
	    	}
		},
	    build: function (grid, op) {
	    	if(op.rowRender){
	    		var render = IGrid.rowRender.get(op.rowRender);
	    		render && render.build(grid, op);
	    	}
	    },
	    clear: function (grid, op) {
	    	if(op.rowRender){
	    		var render = IGrid.rowRender.get(op.rowRender);
	    		render && render.clear && render.clear(grid, op);
	    	}
	    },
	    individuation: function (grid, op, gridProps, columnProps, propOp) {
			if (op.allowSort && op.remoteSort && (op.rowRender == "group" || op.rowRender == "rowSpan")) {
				var rowRenderOp = op.rowRenderOp,
					spareFields = rowRenderOp && rowRenderOp.spareFields,
					orderArray = rowRenderOp && rowRenderOp.order || [],
					rowRenderName = (op.rowRender == "group") ? rowRenderMsg.groupCol : rowRenderMsg.rowSpanCol,
					setComboData = rowRenderIndividuation.setComboData(orderArray, spareFields, op._columnMap),
					sortMsg = IGrid.Const.I18n.header, tempValue;
				//  添加相同数据验证
				Ccay.Validator.addRule("isSameValue", function (value, params, element) {
					var grid = IGrid.Helper.getGridObj(element),
						// 获取选中的值
						selectValue = element.manager().getValue(),
						// 获取单元格的值
						cellValue = element.data("caller").attr("val"), sameValues;
					if (selectValue != cellValue) {
						sameValues = grid.op.Storage.filter(function(item, i){
							return (item.field == selectValue) ? true : false;
			    		});
						return sameValues.length ? false : true;
					}
					return true;
				}, $i18n(rowRenderMsg.noSelectedMsg));
				// 设置个性化参数
				gridProps.rowRenderOp.ePropName = rowRenderMsg.rowRenderSet;
				gridProps.rowRenderOp.order = {
					type: "arrayEditor",
					ePropConf: orderArray,
					ePropName: rowRenderName,
					ePropDesc: rowRenderMsg.rowRenderMsg,
					editorOp: {
						width : 518,
						usingEsc: false,
						fnRowDrag: function (e, pos, mover, trigger, op) {
							// 验证不通过，禁用拖拽功能
							if (!this.valid()) {
								return false;
							}
						},
						columns:[{
							field: "field",
							header: rowRenderName,
							width: 150,
							rule: {required: true, isSameValue: true},
							type: "enum",
							format: {data: setComboData}
						}, {
							field: "sort",
							header: sortMsg.sortType,
							width: 80,
							cssName: "center",
							type: "enum",
							format: {
								data: [
									{value: "asc", text: $i18n(sortMsg.sortAsc)}, 
									{value: "desc", text: $i18n(sortMsg.sortDesc)}
								]
							},
							editorOp : {
								conf : {combo: false}
							},
							defaultValue: {sort: "asc"}
						}]
					}
				};
			}
		}
	});
	
	var rowRenderIndividuation = {
		// 设置渲染数据
		setComboData : function (orderArray, spareFields, columnMap) {
			var setComboData = [],
			// 设置临时保存字段的数组，若候选字段存在，则合并到排序数组中，并去除重复数据
				tempFields = spareFields ? orderArray.concat(spareFields).clearRepeating() : orderArray;
			if (tempFields.length > 0) {
				// 遍历临时保存的字段
				$.each(tempFields, function (sIdx, spareField) {
					// 若当前临时字段是当前列，则需设置在下拉框列表中
					if ($.isPlainObject(spareField)) {
						setComboData.push({value: spareField.field, text: $i18n(columnMap[spareField.field].header)});
					} else {
						setComboData.push({value: spareField, text: $i18n(columnMap[spareField].header)});
					}
				});
			}
			return setComboData;
		}
	};
	
	/** 给grid manager 扩展收缩展开的接口 */
	Ccay.UI.XControl.extendIManager("XGrid", {
		expand : function(isExpand){
			var allTrs = this.getRows(), groupTrs = allTrs.filter(".grid-row-group");
			if(isExpand === false){
				allTrs.filter(".grid-row").hide();
				groupTrs.find("a.group-open").removeClass("group-open");
				groupTrs.not("[groupIndex=0]").hide();
			}else{
				allTrs.filter(".grid-row").show();
				groupTrs.show().find("a.igrid-group").addClass("group-open");
			}
		}
	});
	
	/*********************    行分组 插件注册   开始         *****************/
	//注册树形行渲染器
	IGrid.rowRender.add("group",{
		
		init : function(grid, op){
			
			op.rowRenderOp = $.extend({
				_groupHeader : {},
				_groupValueFn : {},
				order : []
			},op.rowRenderOp)

			var order = op.rowRenderOp.order;

			var grouped = {}, order = op.rowRenderOp.order;
			for(var i = 0,field; field = order[i];i++){
				order[i] = {field : field, sort : "asc"};
				grouped[field] = order[i];
			}
			for(var i=0,col; col = op.columns[i];i++){
				if(grouped[col.field]){
					grouped[col.field].sort = getSortType(col.sort);
				}
				if(col.group && !grouped[col.field]){
					order.push({field : col.field , sort : getSortType(col.sort)});
				}
				col.sort = null;
			}
		},
		
		

		
		build:function(grid,op){
			if(!op.handler.changeTmpl){
				op.handler.changeTmpl = $.Callbacks();
			}
			op.handler.changeTmpl.add(groupGrid.groupRender)
			op.handler.setColumn.add(this.colSet);
			op.handler.dataProcess.add(groupGrid.dataProcess);
			op.handler.initComplete.add(groupGrid.groupRender);
			op.handler.click.add("groupToggle", groupGrid.groupToggle);
			op.handler.click.add("groupSelect", groupGrid.groupSelect);
			op.handler.click.add("groupClick", groupGrid.groupClick);
			op.handler.afterBindData.add( groupGrid.initToggleStype ); 
			//如果该grid支持数据新增，则在插入新记录的时候，做一些特别处理，比如适配插入数据的位置，填充默认数据
			if(op.operation && op.operation.insert){
				setTimeout(function(){
					op.operation.insert._getInsertSet = groupGrid.getInsertSet;
				},100);
			}
			
			//设置自定义排序处理逻辑
			op.fnSort = groupGrid.sort;
		},
		//设置节点列
		colSet:function(grid, col, op){
			var order = op.rowRenderOp.order;
			col.group = false;
			$.each(order, function(i, field){ 
				if(field.field == (col.field)){
					col.group = true;
				}
			})
			var field = col.field, rowOp = op.rowRenderOp, inOrder = false;
			if(col.group || (rowOp.spareFields && rowOp.spareFields.contains(field))){
				rowOp._groupHeader[field] = col.header;
				if(col.expand === false){
					rowOp.unExpand = field;
				}
				if(typeof col.getGroupValue == "function"){
					rowOp._groupValueFn[field] =  col.getGroupValue;
				}
			}
		},
		
		clear : function(grid, op){
			op.rowRenderOp._groupHeader = {};
			op.rowRenderOp._groupValueFn = {}; 
		}
		
	});
	var groupGrid = {
		/**数据绑定前，处理分组逻辑，添加分组行数据
		 */
		dataProcess:function(op){
			
			// datas 原始渲染数据， result 保存处理分组后的数据  cache 用与提高分组计算效率用的缓存对象，保存实际分组值， field:分组列字段名称
			var datas = this, renderOp = op.rowRenderOp, fields = renderOp.groupFields || getFields(renderOp.order),
			groups = renderOp.groups = {};
			//如果当前关闭了分组，则直接return，不做任何处理
			if(op.rowRenderOp.disabled || this.length == 0 || !fields || fields.length == 0){
				return this;
			}

			
			// 如果设置了分组参数，则需要分析并处理数据对象
			var gRecord, compareValue,currValue, cache, result;
			for(var i = 0, field; field = fields[i]; i++ ){
				gRecord = compareValue = currValue = void 0, cache={}, result = [];
				for (var j = m = 0, data; data = datas[j]; j ++, m ++) {
					//判断该数据是分组动态添加的数据（多列分组会出现该情况）
					if("_group" in data){
						compareValue = void 0;
						result.push(data);
						m -- ;
						continue;
					}
					currValue = Ccay.DataHelper.getObj(field, data);
					if(renderOp._groupValueFn[field]){
						currValue =  renderOp._groupValueFn[field].call(null, currValue, data)
					}

					if(compareValue !== currValue){
						gRecord={"_temp": true,"_group" : currValue,"_count" : 0, "_field" : field, "_groupIndex" : i, "_header" : renderOp._groupHeader[field]};
						result.push(gRecord); //添加新的分组标签行数据
						compareValue = currValue; //缓存该分组值，如果改值已经存在，下一条数据的时候，将不在添加分组标签行
						//如果是多列分组并并是默认打开着的
						groups[field] = groups[field] || []
						groups[field].push( m );
					}
					gRecord._count ++;
					result.push(data); //加上原始数据行
				}
				datas = result;
				
			}
			return  datas;
		},
		/** 分组行渲染
		 * 
		 */
		groupRender:function(grid, op){
			//如果当前关闭了分组，则直接return，不做任何处理
			if(!op.rowRenderOp.disabled && op.rowRenderOp.order){
				var colspan, freezeColTmpl = ["<% if('_group' in data){index--;%><tr class='grid-row-group' field='${#_field}' groupValue='${_group}'  groupIndex='${#_groupIndex}' eno='groupClick' >"],selectTmpl=[];
				op.showSeq && freezeColTmpl.push("<td class='grid-cell grid-col0 grid-cell-toggle'></td>");
				var hasSeq = false, hasMulti = false;
				if(op.rowRenderOp.groupSelect!==false){
					for(var i = 0, col; col = op.columns[i]; i++){
						if(col.columnType == 'select' && col.multi ){
							hasMulti = true;
							IGrid.Factory.Column.setTmpl(col,selectTmpl);
						}
					}
				}
				
				colspan = grid.getHeadPanel().find("td[field].grid-cell").length;
				if(selectTmpl.length < 1 && freezeColTmpl.length > 1){
					freezeColTmpl.pop();
				}	
				
				$.each(op.columns,function(i, col){
					if((col.inner || col.columnType) && (col.columnType!="select" || !col.multi ) ){
						colspan ++;
					}
					if(col._ctype == "Seq"){
						hasSeq = true;
					}
				});
				
				if(hasSeq && hasMulti){
					colspan --;
				}
				if(op.rowRenderOp.groupSelect === false){
					colspan ++;
				}
				//根据配置参数，判断默认展开或收缩
				var toogle = '<a  class="igrid-group group-open igrid-group-${#_groupIndex}" eno="groupToggle">';
				var groupTmpl = op.rowRenderOp.groupTmpl || " ${_header} : </a>  ${_group} (${#_count}) ";
				freezeColTmpl.push(selectTmpl.join("").replace("rowSelect","groupSelect"), "<td colspan='${", colspan, "}'  class='grid-cell'>", toogle,groupTmpl, "","</td></tr><% }else{ %>" , op.tmpl ,"<% } %>");
				op.tmpl = freezeColTmpl.join("");
			}
			
		},

		/** 初始化分组行的展开与收缩样式，或隐藏内部行*/
		initToggleStype : function(grid, op){
			if(!op.rowRenderOp.disabled && op.rowRenderOp.unExpand){
				var allTrs = grid.getRows();
				allTrs.filter(".grid-row").hide();
				groupTrs = allTrs.filter(".grid-row-group");
				var groupIndex = groupTrs.filter("[field='" +op.rowRenderOp.unExpand+ "']").attr("groupIndex") * 1;
				
				if(op.rowRenderOp.simpleSort && op.rowRenderOp.groupFields){
					allTrs.find("a.group-open").removeClass("group-open");
					return;
				}
				groupTrs.each(function(){
				  var ctr = $(this), index = ctr.attr("groupIndex") * 1;
				  if( index > groupIndex){
				  	//隐藏子分组行，并且修改toogle样式
				  	ctr.hide().find("a.group-open").removeClass("group-open");
				  }else if( index == groupIndex){
				  	//当前分组，只需要修改toogle样式即可
				  	ctr.find("a.group-open").removeClass("group-open");
				  }
				});
			}
			
			//全选事件扩展
			grid.getHeadTable().find("td.igrid-selectAll").click(function(){
				 if(!$(this).parent().hasClass("igrid-selected")){
				 	grid.getBodyTable().find("tr.grid-row-group").addClass("igrid-selected");
				 }else{
				 	grid.getBodyTable().find("tr.grid-row-group").removeClass("igrid-selected");
				 }
			});
		},
		/** 收缩 展开 分组
		 */
		groupToggle:function(e, trigger, grid){
	 		e.stopPropagation();
	 		if(!grid.valid()){
	 			return;
	 		}
	 		var isClose = !trigger.hasClass('group-open') , tr = trigger.parents('tr:first'), currgroupFields = tr.attr("field"), 
	 		groupIndex = tr.attr("groupIndex") * 1, nextTr = tr.next(), allTrs = [];
	 		
	 		trigger.toggleClass("group-open");

	 		//将需要改变状态的行全部添加到 allTrs 中，统一操作
	 		while(  nextTr.hasClass("grid-row") ||  nextTr.attr("groupIndex") * 1 > groupIndex ){
	 		    allTrs.push( nextTr[0] );
	 			nextTr = nextTr.next();
	 		}
	 		allTrs = $(allTrs);
	 		isClose ? allTrs.show() : allTrs.hide(); 
	 		//如果存在子分组，则隐藏所有grid-row 并修改子分组样式
	 		if( tr.next("tr.grid-row-group").attr("groupIndex") * 1 > groupIndex ){
	 			allTrs.filter(".grid-row").hide();
	 			allTrs.filter(".grid-row-group").find("a.group-open").removeClass("group-open");
	 		}
	 		var body = grid.getBodyPanel();
	 		if(body[0]&& body[0].style && !body[0].style.height && !body[0].style.maxHeight){
	 			grid.getBodyPanel().css("overflow-y","hidden")
	 		}
		},
		/**选择组
		 */
		groupSelect:function(e, trigger, grid){
			
			var tr = trigger.parent("tr:first"), selected = !tr.hasClass(Const.selected.css) , nextTr=tr.next("tr");
			var groupIndex = tr.attr("groupIndex") * 1;
			tr.toggleClass(Const.selected.css, selected);
	 		//选中或取消选中 该group下面所有的数据行
	 		while(nextTr.length > 0 && ( !nextTr.hasClass("grid-row-group") || nextTr.attr("groupIndex") * 1 > groupIndex ) ){
	 			if(nextTr.hasClass("grid-row-group")){
	 				nextTr.toggleClass(Const.selected.css,selected);
	 			}else{
	 				IGrid.innerColumn.gridSelect.rowSelected(nextTr, selected, grid);
	 			}
	 			nextTr = nextTr.next("tr");
	 		}
		},
		/** 点击分组行事件 */
		groupClick:function(e, trigger, grid){
			grid.getBodyTable().find( "tr.grid-row.igrid-actived,tr.grid-row-group.igrid-actived-group" ).removeClass("igrid-actived igrid-actived-group");
			var tr = $.getEventTarget(e).parent( "tr" ).addClass( "igrid-actived-group" );
		},
		
		getInsertSet:function(grid, op){
	   		var setting = {scroll : false},posTr = grid.getFocusRow();
	   		if(posTr[0]){
	   			posTr = setting.posTr = posTr.prevAll( "tr.grid-row-group:first" ).next();
	   		}else{
	   			posTr = setting.posTr = grid.getBodyTable().find("tr.grid-row-group.igrid-actived-group" ).next();
	   			while( posTr.hasClass("grid-row-group")){
	   				posTr = setting.posTr  =  posTr.next();
	   			}
	   			
	   			
	   		}
	   		
	   		if(posTr.length == 0){
	   			posTr =  setting.posTr = null;
	   		} 
	   		setting.dataHandle = function(record,grid){
	   			if(this.posTr){
		   			var groupTr = this.posTr.prevAll( "tr.grid-row-group:first" );
		   			while( groupTr.length > 0 ){
		   				var groupIndex = groupTr.attr("groupIndex") * 1;
		   				Ccay.DataHelper.setObj(groupTr.attr( "field" ), record, groupTr.attr("groupValue"));
		   				if(groupIndex <= 0){
		   					break;
		   				}
		   				groupTr = groupTr.prevAll( "tr.grid-row-group[groupIndex="+ ( --groupIndex ) +"]:first" );
		   			}
	   			}
			}
	   		return setting;
		},
		
		/** 分组排序处理逻辑 */
		sort : function(sortField,sort,cell){
			this.clearSortSetting();
			var factSortField  = cell.attr("field");
			if(!factSortField){
				return;
			}
			// 是否开启了简单排序，如果开启，则取消分组
			var renderOp = this.op.rowRenderOp, orderFields = renderOp.order;
			if(!renderOp.groups || this.length == 0){
				return;
			}
			if( renderOp.simpleSort ){
				//如果启用了简单排序
				if(renderOp.spareFields && renderOp.spareFields.contains( factSortField )){
					 renderOp.groupFields = [factSortField];
					 if(renderOp.disabled){
					 	renderOp.disabled = false;
					 	//关闭分组后重新开启分组需要重新生成html tr模板
					 	groupGrid.groupRender(this, this.op);
					 }
				}else if(this.op._columnMap[factSortField].group){
					//如果是分组列排序，则排序后，只按当前排序列分组
				    renderOp.groupFields = [factSortField];
				    renderOp.disabled = false;
				    //非分组模式下拖拽后，点击分组列排序，从从非分组模式 转向 分组模式，需要修正op.tmpl模板，否则会报错
				    if(this.op.colsort !== false){
				   	  groupGrid.groupRender(this, this.op);
				    }
				}else{
					//平且排序列非是分组列，则设置标记，排序后，将不分组处理
					renderOp.disabled = true;
				}
				return true;
			}else if( orderFields[0] && orderFields[0].field == factSortField){
				 // 如果是第一优先级的分组列排序，则按照原有逻辑处理
				return true;
			}else{
				
				if(this.op.remoteSort){
					//服务端模式下，生成排序规则，并且交予原有排序逻辑处理
					var  sorts=[];
					$.each(orderFields ,function(i, item){
						if( item.field != factSortField ){
							sorts.push(item);
						}else{
							return false;
						}
					});
					sorts.push({field : factSortField, sort : sort});
					this.setSortSetting(sorts, true);
					return;
				}
				
				
				var preField, sections, dataset = this.op.Storage.dataset;
				// 如果排序分组行
				$.each(orderFields,function(i, item){
					if( item.field == factSortField ){
						preField =  orderFields[i - 1].field;
						return false;
					}
				});
				preField = preField || orderFields[ orderFields.length - 1];
				sections = renderOp.groups[ preField ];
				if( sections ){
					sections.push( dataset.length );
					for(var i = 1; i < sections.length; i ++ ){
						//调用原有排序功能进行区间排序
						this.op.Storage.sort(sortField, sort, sections[i - 1] , sections[i] - 1)
					}
					renderOp.disabled = null;
					this.reload();
					!this.op._loadType && (this.op._loadType = "sort");
					return false; //阻止原生功能排序
				}
			}
			
		}

	};

	
	/*********************   结束    *****************/
	
	/*********************  行合并 渲染插件 开始    *****************/
	
	//注册树形行渲染器
	IGrid.rowRender.add("rowSpan",{
		
		//设置节点列
		init:function(grid, op){
			op.rowRenderOp = $.extend({
				order : []
			},op.rowRenderOp)

			var spaned = {}, order = op.rowRenderOp.order;
			for(var i = 0,field; field = order[i];i++){
				order[i] = {field : field, sort : "asc"};
				spaned[field] = order[i];
			}
			for(var i=0,col; col = op.columns[i];i++){
				if(spaned[col.field]){
					spaned[col.field].sort = getSortType(col.sort);
				}
				if(col.rowSpan && !spaned[col.field]){
					order.push({field : col.field , sort : getSortType(col.sort)});
				}
				col.sort = null;
			}
			
			if(op.rowRenderOp.priority === false){
				op.rowRenderOp.simpleSort = true;
			}
		},
		build:function(grid,op){
			op.handler.setColumn.add(this.colSet);
			op.handler.dataProcess.add(rowSpanGrid.dataProcess);
			op.Storage.Trigger.store.add(function(){
				op.rowRenderOp.groups = {};
			});
			op.__fnBeforeEdit = op.fnBeforeEdit;
			//重写编辑前置事件，处理还原列合并操作
			op.fnBeforeEdit = rowSpanGrid.fnBeforeEdit;
			op._fnEndInsertRow = rowSpanGrid.fnEndInsertRow;
			//设置自定义排序处理逻辑
			op.fnSort = rowSpanGrid.sort;
		},
		//设置节点列
		colSet:function(grid, col, op){
			var spanField = col.field;
			var order = op.rowRenderOp.order;
			col.rowSpan = false;
			$.each(order, function(i, field){
				if(field.field == spanField){
					col.rowSpan = true;
				}
			})
			if(col.rowSpan){
				col.attr.rowspan = "${#data._" + rowSpanGrid.encode(spanField) + "_rowSpan}";
				col.cssName += "${#data._" + rowSpanGrid.encode(spanField) + "_rowSpanHide} ${# data._" + rowSpanGrid.encode(spanField) + "_rowSpan>1 ? 'igrid-rowspan' : ''}${delete data._newRowSpan && delete data._"  
				+ rowSpanGrid.encode(spanField) + "_rowSpanHide && delete data._" + rowSpanGrid.encode(spanField) + "_rowSpan ? '' : ''  }";
			}
		},
		
		clear : function(grid, op){
			op.__fnBeforeEdit = op.fnBeforeEdit;
		}

	});
	
	var rowSpanGrid = {
		
		/**数据绑定前，处理行合并逻辑
		 */
		dataProcess : function(op){
			if(op.rowRenderOp.disabled){
				return this;
			}
			// datas 原始渲染数据， result 保存处理分组后的数据  cache 用与提高分组计算效率用的缓存对象，保存实际分组值， field:分组列字段名称
			var datas = this, order =  op.rowRenderOp.rowSpanFields || op.rowRenderOp.order || [],
			groups = op.rowRenderOp.groups = {};
	
			$.each(order,function(i, item){
				var field = item.field;
				// 如果设置了分组参数，则需要分析并处理数据对象
				var spanValue= void 0, num = 1, firstSpanData = void 0;
		
				if(op._columnMap && op._columnMap[field] && op._columnMap[field].hidden){
					return;
				}
				if(!field ||  datas.length === 0){
					return false;
				}
				
				$.each(datas,function(j, data){  
					var currValue = Ccay.DataHelper.getObj(field, data),updated;
					if(data._update &&  data._updFields && _updFields.contains(field)){
						updated = true;
					}else{
						updated = false;
					}
					if((!firstSpanData || !firstSpanData._inserted) && !data._inserted && !updated && !data._updated && spanValue === currValue &&  (op.rowRenderOp.priority === false ||  !data._newRowSpan)){
						num ++;
						data["_"+rowSpanGrid.encode(field)+"_rowSpanHide"] = " hide"; //需要合并的列，就添加隐藏的标识
						firstSpanData["_"+rowSpanGrid.encode(field)+"_rowSpan"] = num > 1 ? num : null;
					}else{
						spanValue = currValue;
						num = 1;
						firstSpanData = data;
						firstSpanData._newRowSpan = true;
						
						//只有开启优先级排序
						if( !op.rowRenderOp.simpleSort  ){
							groups[field] = groups[field] || []
							groups[field].push( j );
						}
					}
				})
			});
			return  datas;
		},
		
		encode : function(fieldName){
			return fieldName.replaceAll("\\.", "\_");
		},
		
		/** 合并单元格编辑之前，将之分开，并开启第一个单元格编辑 */
		fnBeforeEdit : function(value, td, col, rowData){
			if(col.rowSpan){
				var rowspan=td.attr("rowspan")*1,nextTd=td;
				if(rowspan>1){
					for(var i=1;i<=rowspan;i++){
						nextTd=nextTd.parent().next().find("td[_col="+col.attr._col+"]").removeClass("hide");
					}
					td.attr("rowspan",1).removeClass("igrid-rowspan");
				}
			} 
			if (this.op.__fnBeforeEdit){
				return this.op.__fnBeforeEdit.call(this, value, td, col, rowData);
			}
		},
		
		
		fnEndInsertRow : function(newTr, setting, record){
			var  posTr = $(setting.posTr),hideTd=$([]);
   			var fields = getFields(this.op.rowRenderOp.order);
   			for(var i = 0, field; field = fields[i]; i++){
   				var newTd = newTr.children("td[rowspan][field='"+field+"']"),
   				_col = newTd.attr("_col"),posTd =posTr.children("td[_col="+_col+"]")
   				if(newTr.next().children("td[rowspan=1][_col="+_col+"].hide").length > 0){
   					var prevTr = newTr.prev(),prevTd;
	   				while(prevTr.length > 0){
						prevTd = prevTr.find("td[_col="+_col+"]");
						if(prevTd.is("td[rowspan=1].hide")){
							prevTd.removeClass("hide");
						}else{
							prevTd.attr("rowspan",1).removeClass("igrid-rowspan");
							break;
						}
						prevTr = prevTr.prev();
					}
					var nextTr = newTr.next(),nextTd;
					while(nextTr[0]){
						nextTd = nextTr.find("td[rowspan=1][_col="+_col+"].hide");
						if(nextTd[0]){
							nextTd.removeClass("hide");
						}else{
							break;
						}
						nextTr = nextTr.next();
					}
   				}

   			}
		
		},
		
		/** 行合并排序处理逻辑 */
		sort : function(sortField,sort,cell){
			this.clearSortSetting();
			var factSortField = cell.attr("field"), renderOp = this.op.rowRenderOp, orderFields =  renderOp.rowSpanFields ||renderOp.order || [];
			
			//当存在合并数据组，并且当前数据集含有数据
			if(renderOp.groups && this.op.Storage.dataset.length > 0){
				
				if( renderOp.simpleSort ){
					//如果启用了简单排序 则按原有逻辑
					if(this.op._columnMap[factSortField].rowSpan){
						 renderOp.rowSpanFields = [{field : factSortField, sort : sort}];
						 renderOp.disabled = false;
					}else{
						//如果是非合并列，则设置标志，下次不做合并处理
						renderOp.disabled = true;
					}
					return true;
				}
				//非简单排序，平且当前排序列不是第一优先级的合并列，按照优先级，分段处理排序，否则按照默认排序逻辑
				if(!renderOp.simpleSort && orderFields[0] && orderFields[0].field !== factSortField ){
					if(this.op.remoteSort){
						//服务端模式下，生成排序规则，并且交予原有排序逻辑处理
						var  sorts=[];
						$.each(orderFields ,function(i, item){
							if( item.field != factSortField ){
								sorts.push(item);
							}else{
								return false;
							}
						});
						sorts.push({field : factSortField, sort : sort});
						this.setSortSetting(sorts,true);
						return true;
					}else{
						
						if($.isEmptyObject(this.op.rowRenderOp.groups)){
							rowSpanGrid.dataProcess.call(this.op.Storage.store(),this.op);
						}
						
						//客户端方式，自己实现排序
						var  preField, sections, dataset = this.op.Storage.dataset;
						$.each(orderFields,function(i, item){
							if( item.field == factSortField ){
								preField =  orderFields[i - 1].field;
								return false;
							}
						});
						if(!preField){
							preField = orderFields[ orderFields.length - 1].field;
						}
						sections = renderOp.groups[ preField ];
						if (sections) {
							sections.push( dataset.length );
							for(var i = 1; i < sections.length; i ++ ){
								//调用原有排序功能进行区间排序
								if( sections[i] - 1 - sections[i - 1] > 0){
									this.op.Storage.sort(sortField, sort, sections[i - 1] , sections[i] - 1);
								}
							}
							!this.op._loadType && (this.op._loadType = "sort");
							renderOp.disabled = false;
							this.reload();
							return false; //阻止原生功能排序
						}
						return true;
					}
				}
			}
		}
	};
})(Ccay.UI.IGrid,Ccay.UI.IGrid.Const);


















